<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Operation\Service;

use Doctrine\ORM\EntityManager;
use Operation\Entity\UserCoupon;

class UserCouponManager
{
    private $entityManager;

    public function __construct(
        EntityManager $entityManager
    )
    {
        $this->entityManager = $entityManager;
    }

    /**
     * 添加会员优惠券
     * @param array $data
     * @return UserCoupon
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addUserCoupon(array $data)
    {
        $userCoupon = new UserCoupon();
        $userCoupon->valuesSet($data);

        $this->entityManager->persist($userCoupon);
        $this->entityManager->flush();

        return $userCoupon;
    }

    /**
     * 编辑更新会员优惠券
     * @param array $data
     * @param UserCoupon $userCoupon
     * @return UserCoupon
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editUserCoupon(array $data, UserCoupon $userCoupon)
    {
        $userCoupon->valuesSet($data);
        $this->entityManager->flush();

        return $userCoupon;
    }

    /**
     * 更新购买商品获取的优惠券为可用
     * @param $orderId
     * @param $userId
     */
    public function updateOrderGetUserCoupon($orderId, $userId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->update(UserCoupon::class, 'u')
            ->set('u.couponUseState', ':couponUseState')->setParameter('couponUseState', 1)
            ->where('u.couponUseState = :useState')->setParameter('useState', 0)
            ->andWhere('u.getOrderId = :orderId')->setParameter('orderId', $orderId)
            ->andWhere('u.userId = :userId')->setParameter('userId', $userId);

        $qb->getQuery()->execute();
    }

    /**
     * 根据订单id删除获取的优惠券
     * @param $orderId
     */
    public function deleteUserOrderCoupon($orderId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->delete(UserCoupon::class, 'u')->where('u.getOrderId = :orderId')->setParameter('orderId', $orderId);

        $qb->getQuery()->execute();
    }

    /**
     * 删除对应优惠券id
     * @param $couponId
     */
    public function deleteUserCoupon($couponId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->delete(UserCoupon::class, 'u')->where('u.couponId = :couponId')->setParameter('couponId', $couponId);

        $qb->getQuery()->execute();
    }
}